package com.lightsh.utility.generator;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class LGenerator<T> implements IGenerator<T>{
	public Class<T> mType;
	public Class<?>[] mParamsType;
	public Object[] mParams;
	
	/**
	 * type类型必须有默认构造函数
	 * @param type
	 */
	public LGenerator(Class<T> type){
		mType = type;
	}
	
	/**
	 * 可带参数的generator
	 */
	public LGenerator(Class<T> type, Class<?>[] paramsType, Object[] params){
		this(type);
		mParamsType = paramsType;
		mParams = params;
	}
	
	public static <T> IGenerator<T> createGenerator(Class<T> type){
		return new LGenerator<T>(type);
	}
	
	public static <T> IGenerator<T> createGenerator(Class<T> type, Class<?>[] paramsType, Object[] params){
		return new LGenerator<T>(type, paramsType, params);
	}
	
	public T next() {
		try {
			if(mParamsType != null){
				Constructor<T> con = mType.getConstructor(mParamsType);
				return con.newInstance(mParams);
			}else{
				return mType.newInstance();
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static class Apple{
		String mName;
		public Apple(){
			mName = "i am a normal apple";
		}
		public Apple(String name){
			mName = name;
		}
		public String toString(){
			return mName;
		}
	}
	
	public static class AutoCountClass{
		public static int mCounter = 0;
		public final int mId = mCounter++;
		public String toString(){
			return "my id is " + mId;
		}
	}
	
	public static void main(String[] args) {
		System.out.println("---------------------");
		System.out.println(LGenerator.createGenerator(String.class).next());
		System.out.println(LGenerator.createGenerator(String.class, new Class[]{}, new Object[]{}).next());
		System.out.println(LGenerator.createGenerator(String.class, new Class[]{String.class}, new Object[]{"abc"}).next());
		
		
		System.out.println(LGenerator.createGenerator(Integer.class, new Class[]{int.class}, new Object[]{1}).next());
		
		
		System.out.println(LGenerator.createGenerator(Apple.class).next());
		System.out.println(LGenerator.createGenerator(Apple.class, new Class[]{String.class}, new Object[]{"apple b"}).next());
		
		IGenerator<AutoCountClass> iGenerator = LGenerator.createGenerator(AutoCountClass.class);
		for(int i = 0; i < 100; ++i){
			System.out.println(iGenerator.next());
		}
		
		System.out.println("---------------------");
	}
}
